<?php

/**
 * Mediad co,ltd
 *
 * @category   Mediad2
 * @package    Mediad2_Utility
 * @copyright  Copyright (c) 2012 PS co,ltd. (http://www.Mediad.cn)
 * @license    New BSD License
 * @version    $Id: Abstract.php 2012-02-02 11:19:00Z tany@Mediad.cn $
 */


/**
 * @category   Mediad2
 * @package    Mediad2_Utility
 */
abstract class Mediad2_Utility_Abstract 
{
	/**
	 * result object
	 *
	 * @var Mediad2_Model_Result
	 */
	protected $result;
	
	/**
	 * helper object
	 * 
	 * @var Mediad2_Utility_SmartyHelper
	 */
	protected $helper;
	
	/**
	 * Constructor.
	 *
	 * @return void
	 */
	public function __construct()
	{
		$this->result = new Mediad2_Model_Result();
		$this->helper = new Mediad2_Utility_SmartyHelper();
		$this->init();
	}
	
	/**
	 * Initialize object
	 *
	 * Called from {@link __construct()} as final step of object instantiation.
	 *
	 * @return void
	 */
	public function init()
	{
	}
	
	/**
	 * set result
	 * 
	 * @param string $result
	 * @throws Exception
	 * @return Mediad2_Service_Abstract
	 */
	protected function setResult($result)
	{		
		if (is_string($result)) {
			$result = new $result();
		}

		if (!($result instanceof Mediad2_Model_Result)) {
			throw new Mediad2_Service_Exception('缺少类Mediad2_Model_Result!');
		}
		$this->result = $result;
		return $this;
	}
	
	/**
	 * get result
	 *
	 * @return Mediad2_Model_Result
	 */
	protected function getResult ()
	{
		if (null === $this->result) {
			$this->setResult('Mediad2_Model_Result');
		}
		return $this->result;
	}
	
	/**
	 * return $result
	 * 
	 * @param string $code
	 * @param string $message
	 * @param string $data
	 * @return Mediad2_Model_Result
	 */
	protected function returnResult($code, $message = null, $data = null)
	{
		$result = new Mediad2_Model_Result();
		
		if (!isset($message)) {
			switch ($code) {
				case Mediad2_Model_Result::CODE_SUCCESS:
					$message = Mediad2_Model_Result::MESSAGE_SUCCESS;
					break;
				case Mediad2_Model_Result::CODE_FAILURE:
					$message = Mediad2_Model_Result::MESSAGE_FAILURE;
					break;
				default:
					$message = '';
					break;
			}
		}
		if (!isset($data)) {
			$data = '';
		}
		
		$result->setCode($code);
		$result->setMessage($message);
		$result->setData($data);
		
		return $result;
	}
	
	/**
	 * handle exception
	 * 
	 * @param Zend_Exception $e
	 * @return Mediad2_Service_Abstract
	 */
	protected function handleException(Zend_Exception $e, $debug = false)
	{
		if ($debug) {
			var_dump($e->getMessage());
			return $this;
		} else {
			//出错处理--log
			$registry = Zend_Registry::getInstance ();
			if ($registry->isRegistered('log')) {
				$log = $registry->get('log');
				$log->crit($e->getMessage(), $e);
			}
			//出错处理--邮件
			$em = new Mediad2_Service_Util_Email();
			$em->sendException($e->getMessage());
			return $this;
		}
	}
}